package org.chuan.org.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import org.apache.poi.ss.usermodel.Workbook;
import org.chuan.base.annotation.SelfPermission;
import org.chuan.base.utils.AjaxResult;
import org.chuan.base.utils.PageList;
import org.chuan.org.domain.Employee;
import org.chuan.org.query.EmployeeQuery;
import org.chuan.org.service.IEmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/emp")
@SelfPermission(name = "员工管理")
@CrossOrigin
public class EmployeeController {

    @Autowired
    private IEmployeeService employeeService;

    List<Employee> errorList = new ArrayList<>();

    @GetMapping
    @SelfPermission(name = "查询所有员工")
    public List<Employee> queryAll(){
        try {
            return employeeService.queryAll();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @GetMapping("/{id}")
    @SelfPermission(name = "查询一个员工")
    public Employee queryById(@PathVariable("id") Long id){
        try {
            return employeeService.queryById(id);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @PutMapping
    @SelfPermission(name = "员工的新增或修改")
    public AjaxResult saveOrUpdate(@RequestBody Employee employee){
        try {
            if (employee.getId() == null){
                employeeService.save(employee);
            }else {
                employeeService.update(employee);
            }
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me()
                    .setSuccess(false)
                    .setMessage("操作失败"+e.getMessage());
        }
    }

    @DeleteMapping("/{id}")
    @SelfPermission(name = "员工的删除")
    public AjaxResult delete(@PathVariable("id") Long id){
        try {
            employeeService.delete(id);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me()
                    .setSuccess(false)
                    .setMessage("删除失败"+e.getMessage());
        }
    }

    @PostMapping
    @SelfPermission(name = "员工分页查询")
    public PageList<Employee> queryPage(@RequestBody EmployeeQuery query){
        try {
            return employeeService.queryPage(query);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @PatchMapping
    @SelfPermission(name = "员工批量删除")
    public AjaxResult patchDelete(@RequestBody List<Long> ids){
        try {
            employeeService.batchRemove(ids);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me()
                    .setSuccess(false)
                    .setMessage("删除失败"+e.getMessage());
        }
    }


    @PostMapping("/export")
    public void exportData(@RequestBody EmployeeQuery query, HttpServletResponse response){
        try {
            List<Employee> list = employeeService.querySelf(query.getKeywords());
            ExportParams params = new ExportParams();
            Workbook workbook = ExcelExportUtil.exportExcel(params, Employee.class, list);
            workbook.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @PostMapping("/errorData")
    public void errorData(HttpServletResponse response){
        try {
            ExportParams params = new ExportParams();
            Workbook workbook = ExcelExportUtil.exportExcel(params, Employee.class, errorList);
            workbook.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @PostMapping(value = "/import",consumes = "multipart/form-data")
    public AjaxResult importData(@RequestParam("file") MultipartFile multipartFile){
        try {
            ImportParams importParams = new ImportParams();
            importParams.setHeadRows(1);
            importParams.setHeadRows(2);
            List<Employee> list = ExcelImportUtil.importExcel(multipartFile.getInputStream(),Employee.class,importParams);
            for (Employee employee : list) {
                if (employeeService.isValid(employee.getEmail())){
                    employeeService.save(employee);
                }else {
                    errorList.add(employee);
                }
            }
            if (errorList.isEmpty()){
                return AjaxResult.me();
            }else {
                return AjaxResult.me()
                        .setSuccess(false)
                        .setMessage("有错误数据，正在导出");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me()
                    .setSuccess(false)
                    .setMessage("上传失败");
        }
    }
}
